package com.huhao.wshare.controller;

import com.huhao.wshare.dto.Friend.Request.*;
import com.huhao.wshare.dto.Friend.Response.AcceptFriendResponse;
// 移除了不再需要的 PendingRequestsResponse 导入
import com.huhao.wshare.dto.Friend.Response.SendFriendRequestResponse;
import com.huhao.wshare.entity.User;
import com.huhao.wshare.repository.UserRepository;
import com.huhao.wshare.service.FriendService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus; // 【新增】导入 HttpStatus
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap; // 【新增】导入 HashMap
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/friends")
@RequiredArgsConstructor
public class FriendController {

    private final FriendService friendService;
    private final UserRepository userRepository;

    // ... getCurrentUser, sendFriendRequest, acceptFriendRequest 方法保持不变 ...
    private User getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new IllegalStateException("用户未登录或认证失败");
        }
        String account = ((UserDetails) authentication.getPrincipal()).getUsername();
        return userRepository.findByAccount(account)
                .orElseThrow(() -> new IllegalStateException("在数据库中找不到当前登录用户"));
    }

    @PostMapping("/request")
    public ResponseEntity<Object> sendFriendRequest(@Valid @RequestBody AddFriendRequest request) {
        try {
            Long currentUserId = getCurrentUser().getId();
            FriendRequestInfo resultData = friendService.sendFriendRequest(currentUserId, request);
            SendFriendRequestResponse response = SendFriendRequestResponse.builder()
                    .requesterName(resultData.getRequesterName())
                    .receiverName(resultData.getReceiverName())
                    .remark(resultData.getRemark())
                    .build();
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = Map.of(
                    "code", 400,
                    "message", e.getMessage()
            );
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }

    @PostMapping("/accept/{requestId}")
    public ResponseEntity<Object> acceptFriendRequest(
            @PathVariable Long requestId,
            @RequestBody AcceptFriendRequest request) {
        try {
            Long currentUserId = getCurrentUser().getId();
            AcceptFriendResponse response = friendService.acceptFriendRequest(currentUserId, requestId, request);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = Map.of(
                    "code", 400,
                    "message", e.getMessage()
            );
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }
    /**
     * 【已符合要求】
     * 拒绝或删除一个好友请求。
     * @param requestId 要拒绝的好友请求的ID (从URL路径中获取)
     * @return 包含成功信息的响应体
     */
    @DeleteMapping("/reject/{requestId}")
    public ResponseEntity<Object> rejectFriendRequest(@PathVariable Long requestId) { // <-- 只从URL路径获取requestId
        try {
            Long currentUserId = getCurrentUser().getId();
            // 调用服务层时，没有传递任何来自请求体的数据
            friendService.rejectFriendRequest(currentUserId, requestId);

            Map<String, Object> response = new HashMap<>();
            response.put("code", HttpStatus.OK.value());
            response.put("message", "好友请求已成功拒绝");

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", HttpStatus.BAD_REQUEST.value());
            errorResponse.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }
    /**
     * 获取好友列表的 API 端点，响应体已包装。
     */
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getFriendList() { // 返回类型修改为 ResponseEntity<Map<String, Object>>
        try {
            Long currentUserId = getCurrentUser().getId();
            // 1. Service层返回纯粹的数据列表
            List<FriendListItem> friendList = friendService.getFriendList(currentUserId);

            // 2. 在Controller层构建标准的响应体
            Map<String, Object> response = new HashMap<>();
            response.put("code", HttpStatus.OK.value()); // 200
            response.put("message", "好友列表获取成功");
            response.put("data", friendList); // 将数据列表放入 data 字段

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            // 这里的错误处理可以保留，或者也接入全局异常处理器
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", HttpStatus.BAD_REQUEST.value()); // 400
            errorResponse.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }

    /**
     * 获取所有待处理的好友请求 API 端点，响应体已包装。
     */
    @GetMapping("/requests/pending")
    public ResponseEntity<Map<String, Object>> getPendingFriendRequests() { // 返回类型修改为 ResponseEntity<Map<String, Object>>
        try {
            Long currentUserId = getCurrentUser().getId();
            // 1. Service层返回纯粹的数据列表
            List<PendingFriendRequestItem> pendingList = friendService.getPendingFriendRequests(currentUserId);

            // 2. 在Controller层构建标准的响应体
            Map<String, Object> response = new HashMap<>();
            response.put("code", HttpStatus.OK.value()); // 200
            response.put("message", "待处理的好友请求获取成功");
            response.put("data", pendingList); // 将数据列表放入 data 字段

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", HttpStatus.BAD_REQUEST.value()); // 400
            errorResponse.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }

    @PatchMapping("/{friendId}/remark")
    public ResponseEntity<Object> updateFriendRemark(
            @PathVariable Long friendId,
            @RequestBody UpdateRemarkRequest request) {
        try {
            Long currentUserId = getCurrentUser().getId();
            UpdateRemarkResponse response = friendService.updateFriendRemark(currentUserId, friendId, request);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = Map.of(
                    "code", 400,
                    "message", e.getMessage()
            );
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }
    /**
     * 删除好友
     * @param friendId 要删除的好友的用户ID (从URL路径中获取)
     * @return 包含成功信息的响应体
     */
    @DeleteMapping("/{friendId}")
    public ResponseEntity<Object> deleteFriend(@PathVariable Long friendId) {
        try {
            Long currentUserId = getCurrentUser().getId();
            friendService.deleteFriend(currentUserId, friendId);

            Map<String, Object> response = new HashMap<>();
            response.put("code", HttpStatus.OK.value());
            response.put("message", "好友删除成功");

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", HttpStatus.BAD_REQUEST.value());
            errorResponse.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }
}
